//Remember we're describing how an object of this type would work. We're looking at it's innards.
//
//  MyServicesProvider.m
//  Words2
//
//  Created by Mathieu on 26/06/06.
//  Copyright 2006 __MyCompanyName__. All rights reserved.
//

#import "MyServicesProvider.h"
#import "WordsAppDelegate.h"
#import "Parser.h"
#import "WordMO.h"
#import "ManualGroupMO.h"
#import "BubbleController.h"
#import "Lookup.h"



@implementation MyServicesProvider

-(void)addHighlightedWordService:(NSPasteboard *)pboard
 						userData:(NSString *)data //typed as what we handle
						   error:(NSString **)error
{
	NSString *pboardString;
	NSArray *types;
	BOOL showBubble;
	BubbleController * bubbleController;
	types = [pboard types];
	Lookup *lookerupperer = [[NSApp delegate] lookerupperer];
	
	id propertyList = [pboard propertyListForType:NSStringPboardType];
	NSLog(@"propertylist: %@", propertyList);
	
	// if there's a problem with the data passed to this method
	if(![types containsObject:NSStringPboardType] ||
	   !(pboardString = [pboard stringForType:NSStringPboardType]))
	{
		*error = NSLocalizedString(@"Error: Pasteboard doesn't contain a string.",
								   @"Pasteboard couldn't give a string.");
		// if there's a problem then it'll be sure to tell us!
		return;
	}
	
	//parse the text into individual words, store each in an array.
	NSArray *wordArray = [[Parser arrayOfWordsFromText:pboardString] retain];
	NSLog(@"In the Array: %@", wordArray);
	
	
	//if there is only one word (or two) in the array, then show the word bubble with the word in it
	if([wordArray count] == 1){
		showBubble = YES;
		bubbleController = [[NSApp delegate] bubbleController];
	
	}else{
		showBubble = NO;
	}
	
	NSArray *noDuplicatesWordArray = [[Parser removeDuplicateWordsInArray:wordArray] retain];
	NSLog(@"In the Array without duplicates: %@", noDuplicatesWordArray);

	//check the number of words. If grater than 5 then confirm add with user.
	//enumerate through adding all the objects to the moc with the code below.
	
	NSManagedObjectContext *context = [[NSApp delegate] managedObjectContext];	//give us the Words application's moc
		
	NSEnumerator *arrayEnum = [noDuplicatesWordArray objectEnumerator];
	NSString *nextWord;
	NSString *currentLanguageName = [[[NSApp delegate] currentlySelectedLanguage] valueForKey:@"name"];
	NSError *fetchError = nil; 
	NSArray *fetchedWord;
	Group *selectedGroup = [[NSApp delegate] currentlySelectedGroup];

	//set up the fetch request
	NSEntityDescription *entityDescription = [NSEntityDescription entityForName:@"Word" inManagedObjectContext:context]; 
	NSFetchRequest *request = [[[NSFetchRequest alloc] init] autorelease]; 
	[request setEntity:entityDescription]; 
	
	while(nextWord = [arrayEnum nextObject]){
		//set the predicate for this word
		NSPredicate *predicate = [NSPredicate predicateWithFormat:@"language.name LIKE[c] %@ AND word LIKE[c] %@", currentLanguageName, nextWord];
		[request setPredicate:predicate];
		//perform the request
		fetchedWord = [context executeFetchRequest:request error:&fetchError]; 
		if (fetchedWord == nil) 
		{ 
			NSLog(@"Fetch request had an error.");
			// Deal with error... 
			// use an empty set in the case where something went awry
		} 
		
		if([fetchedWord count] == 0){
			//add the word
			WordMO *word = [NSEntityDescription insertNewObjectForEntityForName:@"Word" inManagedObjectContext:context]; //this does the insertion into the context reserved for 'word' objects.
			[word setValue:nextWord forKey:@"word"];
			[word setValue:[NSDate date] forKey:@"createdOn"];
			[word setValue:[NSNumber numberWithInt:1] forKey:@"timesEncountered"];
			[word setValue:[[NSApp delegate] currentlySelectedLanguage] forKey:@"language"];
			//if the current group is a manual group, add it to it.
			if([selectedGroup isManualGroup]){
				[word addObject:selectedGroup toToManyRelationshipForKey:@"manualGroups"];
			}
			if(showBubble){
				[bubbleController showBubbleWithWord:word];
			}
			//place the word in a language (?)
			//look the word up in any available dictionaries
			//might very well need a specialised lookup
			//[lookerupperer defineWords:[NSArray arrayWithObject:word] inDictionaries:[[[NSApp delegate] inUseDictController] arrangedObjects]];

		}
		else{
			//increment the fetched word
			WordMO *fWord = [fetchedWord objectAtIndex:0];
			[fWord incrementTimesSeen];
			//attempt to define it unless it's already defined
			if(![fWord isDefined]){
				[lookerupperer defineWords:[NSArray arrayWithObject:fWord] inDictionaries:[[[NSApp delegate] inUseDictController] arrangedObjects]];
			}
			if([selectedGroup isManualGroup]){
				[fWord addObject:selectedGroup toToManyRelationshipForKey:@"manualGroups"];
			}
			if(showBubble){
				[bubbleController showBubbleWithWord:fWord];


			}
		}
	}
	


	// release the retained objects
	[wordArray release];
	wordArray = nil;
	[noDuplicatesWordArray release];
	noDuplicatesWordArray = nil;
}

@end
